package com.zqweb.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zqweb.gulimall.order.config.AlipayTemplate;
import com.zqweb.gulimall.order.service.OrderService;
import com.zqweb.gulimall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Arrays;

@RestController
public class AliorderPayListener {
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private OrderService orderService;

    @PostMapping("/payed/notify")// 支付宝以Post方式发起异步通知，早于同步通知
    public String payedNotify(HttpServletRequest request, PayAsyncVo payAsyncVo) throws AlipayApiException {
        System.out.println("进入了异步通知的监听回调方法中...");
        // PayAsyncVo：异步通知时携带的请求参数封装vo
        Map<String, String[]> paramsMap = request.getParameterMap();
        System.out.println("支付宝支付成功后的异步通知信息如下：");
        for (String k : paramsMap.keySet()) {
            System.out.println("请求参数名：" + k + ",请求参数值：" + Arrays.asList(paramsMap.get(k)).toString());
        }

        //获取支付宝POST来的反馈信息
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        /*
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        */

        // 计算得出通知验证结果（验证签名）
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());

        // 根据验签情况，确认是否返回success字符串，若返回success字符串才会将触发return_url生成的数据返回给订单列表页
        if(verify_result){
            // 保存交易流水，并修改订单的状态
            System.out.println("签名验证成功！");
            orderService.handlePayResult(payAsyncVo);
            return "success";// 必须响应success这7个字符，否则会一直异步通知8次
        }else{
            System.out.println("签名验证失败！");
            return "error";// 若验证失败，返回error
        }

    }

}
